<template>
	<div class="system-role-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form ref="roleDialogFormRef" :model="state.ruleForm" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色名称">
							<el-input v-model="state.ruleForm.name" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色标识">
							<template #label>
								<el-tooltip effect="dark" content="用于 `router/route.ts` meta.roles" placement="top-start">
									<span>角色标识</span>
								</el-tooltip>
							</template>
							<el-input v-model="state.ruleForm.sign" placeholder="请输入角色标识" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="角色状态">
							<el-switch v-model="state.ruleForm.status" inline-prompt :active-value="1" :inactive-value="0"
								active-text="启" inactive-text="禁"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="角色描述">
							<el-input v-model="state.ruleForm.description" type="textarea" placeholder="请输入角色描述"
								maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="菜单权限">
							<el-tree ref="treeMenuRef" node-key="id" :data="state.menuData"
								:default-expanded-keys="state.exkey" :default-checked-keys="state.chkey"
								:check-strictly="state.checkStrictly" :props="{ children: 'children', label: showLabel }"
								show-checkbox class="menu-data-tree" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemRoleDialog">
import { reactive, ref } from 'vue';
import { useMenuApi } from '/@/api/menu/index'
import { i18n } from '/@/i18n/index';
import { useRoleApi } from '/@/api/role';
import { ElMessage } from 'element-plus';


const menuApi = useMenuApi();
const roleApi = useRoleApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const treeMenuRef = ref();

// 定义变量内容
const roleDialogFormRef = ref();
const state = reactive({
	ruleForm: {
		id: 0,
		name: '', // 角色名称
		sign: '', // 角色标识
		status: 1, // 角色状态
		description: '', // 角色描述
		menu_id: [] as number[]
	},
	menuData: [] as any[],
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	// 默认选中
	chkey: [] as number[],
	// 默认展开
	exkey: [] as number[],
	// 是否上下级不关联
	checkStrictly: false
});

// 打开弹窗
const openDialog = async (type: string, row: RowRoleType) => {
	state.chkey = [];
	state.exkey = [];
	state.dialog.type = type;
	// 请求用户能获取到的所有权限结构作为基底，请求/menurole/tree
	if (type === 'edit') {
		state.checkStrictly = true;
		// 深拷贝
		state.ruleForm = { ...row };
		// 请求该角色权限结构作为选择体，请求/menurole/role
		await getMenuById(row.id)
		state.dialog.title = '修改角色';
		state.dialog.submitTxt = '修 改';
	} else {
		state.ruleForm = {} as RowRoleType;
		state.checkStrictly = false;
		state.dialog.title = '新增角色';
		state.dialog.submitTxt = '新 增';
		// 清空表单，此项需加表单验证才能使用
		// nextTick(() => {
		// 	roleDialogFormRef.value.resetFields();
		// });
	}
	await getMenuData();
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
// 提交
const onSubmit = async () => {
	await getAllKeys()
	if (state.dialog.type === 'add') {
		await addRole().then(res => {
			ElMessage.success("新增成功");
		}).catch(err => {
			ElMessage.warning("新增失败");
		});
	} else {
		await updateRole().then(res => {
			ElMessage.success("修改成功");
		}).catch(err => {
			ElMessage.warning("修改失败");
		});
	}
	closeDialog();
	emit('refresh');
};
// 获取菜单结构数据
const getMenuData = () => {
	menuApi.getMenu().then(res => {
		state.menuData = res.result;
	})
};
// 获取某角色权限数据
const getMenuById = async (id: number) => {
	await menuApi.getMenuById(id).then(res => {
		res.result.map((v: any) => {
			state.chkey.push(v.id);
			state.exkey.push(v.id);
		})
	})
};
// 树状权限选择器的label国际化处理
const showLabel = (data: any) => {
	return i18n.global.t(data.title);
}
// 树状选择的权限列表
const getAllKeys = () => {
	state.ruleForm.menu_id = [...treeMenuRef.value.getCheckedKeys()]
}
// 请求新增角色接口
const addRole = async () => {
	return await roleApi.addRole(state.ruleForm);
}
// 请求修改角色接口
const updateRole = async () => {
	return await roleApi.updateRole(state.ruleForm)
}
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-dialog-container {
	.menu-data-tree {
		width: 100%;
		border: 1px solid var(--el-border-color);
		border-radius: var(--el-input-border-radius, var(--el-border-radius-base));
		padding: 5px;
	}
}
</style>
